import fs from 'fs';
import path from 'path';
import { RegisteredDevice } from '../types';

// 配对关系接口
interface PairingRelationship {
  id: string;
  device1Id: string;
  device2Id: string;
  device1Name: string;
  device2Name: string;
  device1Type: string;
  device2Type: string;
  createdAt: number;
  lastActivity: number;
  isActive: boolean;
}

// 配对码接口
interface PairingCode {
  code: string;
  deviceId: string;
  expiresAt: number;
  isUsed: boolean;
}

// 数据存储结构
interface DataStore {
  devices: Record<string, RegisteredDevice>;
  pairings: Record<string, PairingRelationship>;
  pairingCodes: Record<string, PairingCode>;
  stats: {
    lastSave: number;
    totalDevices: number;
    totalPairings: number;
  };
  fingerprintToDeviceId?: Record<string, string>; // 新增字段，可选兼容老数据
}

class DataPersistence {
  private dataDir: string;
  private dataFile: string;
  private autoSaveInterval: NodeJS.Timeout;
  private isSaving: boolean = false;

  constructor() {
    this.dataDir = path.join(process.cwd(), 'data');
    this.dataFile = path.join(this.dataDir, 'smartinput-data.json');
    
    // 确保数据目录存在
    if (!fs.existsSync(this.dataDir)) {
      fs.mkdirSync(this.dataDir, { recursive: true });
    }

    // 自动保存间隔（5分钟）
    this.autoSaveInterval = setInterval(() => {
      this.autoSave();
    }, 5 * 60 * 1000);
  }

  /**
   * 加载数据
   */
  loadData(): DataStore {
    try {
      if (fs.existsSync(this.dataFile)) {
        const data = fs.readFileSync(this.dataFile, 'utf8');
        const parsed = JSON.parse(data);
        
        // 验证数据完整性
        if (this.validateData(parsed)) {
          console.log('✅ 数据加载成功');
          return parsed;
        } else {
          console.warn('⚠️ 数据文件损坏，使用默认数据');
        }
      }
    } catch (error) {
      console.error('❌ 数据加载失败:', error);
    }

    // 返回默认数据结构
    return {
      devices: {},
      pairings: {},
      pairingCodes: {},
      stats: {
        lastSave: Date.now(),
        totalDevices: 0,
        totalPairings: 0
      },
      fingerprintToDeviceId: {} // 新增默认值
    };
  }

  /**
   * 保存数据
   */
  async saveData(data: DataStore): Promise<void> {
    if (this.isSaving) {
      console.warn('⚠️ 正在保存中，跳过重复保存');
      return;
    }

    this.isSaving = true;
    
    try {
      // 更新统计信息
      data.stats = {
        lastSave: Date.now(),
        totalDevices: Object.keys(data.devices).length,
        totalPairings: Object.keys(data.pairings).length
      };

      // 写入临时文件，然后重命名（原子操作）
      const tempFile = this.dataFile + '.tmp';
      await fs.promises.writeFile(tempFile, JSON.stringify(data, null, 2));
      await fs.promises.rename(tempFile, this.dataFile);
      
      console.log('💾 数据保存成功');
    } catch (error) {
      console.error('❌ 数据保存失败:', error);
      throw error;
    } finally {
      this.isSaving = false;
    }
  }

  /**
   * 自动保存
   */
  private autoSave(): void {
    // 这个方法会被 DeviceManager 和 PairingManager 调用
    console.log('🔄 执行自动保存...');
  }

  /**
   * 验证数据完整性
   */
  private validateData(data: any): data is DataStore {
    return (
      data &&
      typeof data === 'object' &&
      typeof data.devices === 'object' &&
      typeof data.pairings === 'object' &&
      typeof data.pairingCodes === 'object' &&
      typeof data.stats === 'object' &&
      (typeof data.fingerprintToDeviceId === 'object' || typeof data.fingerprintToDeviceId === 'undefined')
    );
  }

  /**
   * 备份数据
   */
  async backupData(): Promise<string> {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const backupFile = path.join(this.dataDir, `backup-${timestamp}.json`);
    
    try {
      if (fs.existsSync(this.dataFile)) {
        await fs.promises.copyFile(this.dataFile, backupFile);
        console.log(`💾 数据备份成功: ${backupFile}`);
        return backupFile;
      } else {
        throw new Error('数据文件不存在');
      }
    } catch (error) {
      console.error('❌ 数据备份失败:', error);
      throw error;
    }
  }

  /**
   * 恢复数据
   */
  async restoreData(backupFile: string): Promise<void> {
    try {
      if (!fs.existsSync(backupFile)) {
        throw new Error('备份文件不存在');
      }

      // 验证备份文件
      const data = JSON.parse(fs.readFileSync(backupFile, 'utf8'));
      if (!this.validateData(data)) {
        throw new Error('备份文件格式无效');
      }

      // 恢复数据
      await fs.promises.copyFile(backupFile, this.dataFile);
      console.log('✅ 数据恢复成功');
    } catch (error) {
      console.error('❌ 数据恢复失败:', error);
      throw error;
    }
  }

  /**
   * 清理过期数据
   */
  cleanupExpiredData(data: DataStore): void {
    const now = Date.now();
    let cleanedCount = 0;

    // 清理过期的配对码
    for (const [code, pairingCode] of Object.entries(data.pairingCodes)) {
      if (now > pairingCode.expiresAt) {
        delete data.pairingCodes[code];
        cleanedCount++;
      }
    }

    // 清理离线设备（超过24小时）
    const deviceTimeout = 24 * 60 * 60 * 1000; // 24小时
    for (const [deviceId, device] of Object.entries(data.devices)) {
      if (!device.isOnline && (now - device.lastSeen) > deviceTimeout) {
        delete data.devices[deviceId];
        cleanedCount++;
      }
    }

    if (cleanedCount > 0) {
      console.log(`🧹 清理了 ${cleanedCount} 条过期数据`);
    }
  }

  /**
   * 销毁服务
   */
  destroy(): void {
    if (this.autoSaveInterval) {
      clearInterval(this.autoSaveInterval);
    }
  }
}

export default DataPersistence; 